# !/usr/bin/env python
# -*- coding:utf-8 -*-

import re
import os
import json
from PyQt6.QtCore import pyqtSignal
from PyQt6.QtWidgets import QDialog
from page.name import Ui_name
from service.tishi_Svc import Tishi     # 提示逻辑
from service.public_Svc import *


# ==============================================================================
# page 8.替换名称页面
# ==============================================================================

class Name_add(QDialog, Ui_name):
    """替换名称页面"""
    confirmed_signal_nm = pyqtSignal()

    def __init__(self, name=None):
        super().__init__()
        self.setupUi(self)  # 直接调用self的setupUi方法
        self.name = name
        self.ts = Tishi()  # 提示框

    def edit(self):
        """反显编辑页面信息"""
        self.chaxun1.setText(self.name)
        with open(TEXT_JSON, 'r', encoding='utf-8') as f:
            data = json.load(f)
            value = data.get(self.name, '')              # 获取name的数据
            self.chaxun2.setText(value)

    def contains_invalid_filename_chars(self,filename):
        '''检查是否包含Windows文件命名违禁字符'''
        invalid_chars_pattern = r'[\\/:*?"<>|]'        # 定义违禁字符的正则表达式模式
        if re.search(invalid_chars_pattern, filename):        # 使用re.search()查找匹配项
            return True
        else:
            return False

    def save_name(self):
        """name保存"""
        if len(self.chaxun1.text()) == 0:
            self.ts.xinxi("请填写名称")
            return
        if self.contains_invalid_filename_chars(self.chaxun2.text()):
            self.ts.xinxi('不能包含以下字符：\ / : * ? " < > |')
            return
        data = {self.chaxun1.text():self.chaxun2.text()}
        try:
            if not os.path.exists(TEXT_JSON):
                # 文件不存在，直接写入新数据
                with open(TEXT_JSON, 'w', encoding='utf-8') as f:
                    json.dump(data, f)
            else:
                # 文件存在，读取并合并数据
                with open(TEXT_JSON, 'r', encoding='utf-8') as f:
                    existing_data = json.load(f)
                if self.name:
                    del existing_data[self.name]
                existing_data.update(data)
                # 写回更新后的数据
                with open(TEXT_JSON, 'w', encoding='utf-8') as f:
                    json.dump(existing_data, f)
            self.close()
            self.ts.xinxi(f"保存成功")
        except Exception as e:
            self.ts.xinxi(f"保存出错：{e}")



    def closeEvent(self, QCloseEvent):
        """窗口关闭"""
        self.confirmed_signal_nm.emit()  # 发射查询信号
